package com.rd.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rd.dto.Result;
import com.rd.entity.SeckillVoucher;
import com.rd.entity.Voucher;
import com.rd.mapper.VoucherMapper;
import com.rd.service.SecKillVoucherService;
import com.rd.service.VoucherService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

import static com.rd.utils.RedisConstants.SECKILL_STOCK_KEY;

@Service
public class VoucherServiceImpl extends ServiceImpl<VoucherMapper, Voucher> implements VoucherService {


    @Resource
    private SecKillVoucherService secKillVoucherService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryVoucherOfShop(Long shopId) {
        List<Voucher> vouchers = getBaseMapper().queryVoucherOfShop(shopId);
        return Result.ok(vouchers);
    }

    @Transactional
    @Override
    public void addSecKillVoucher(Voucher voucher) {
        // 保存优惠券到数据库
        save(voucher);
        // 保存秒杀信息到数据库
        SeckillVoucher seckillVoucher = new SeckillVoucher();
        seckillVoucher.setVoucherId(voucher.getId());
        seckillVoucher.setStock(voucher.getStock());
        seckillVoucher.setBeginTime(voucher.getBeginTime());
        seckillVoucher.setEndTime(voucher.getEndTime());
        secKillVoucherService.save(seckillVoucher);
        //保存秒杀库存到redis
        stringRedisTemplate.opsForValue().set(SECKILL_STOCK_KEY + voucher.getId(), voucher.getStock().toString());
    }
}
